<script setup lang="ts">
import { computed, reactive } from 'vue';
import { $t } from '@/locales';
import { useRouterPush } from '@/hooks/common/router';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { useCaptcha } from '@/hooks/business/captcha';
import { useAuthStore } from '@/store/modules/auth';

defineOptions({
  name: 'CodeLogin'
});
const authStore = useAuthStore();

const { toggleLoginModule } = useRouterPush();
const { formRef, validate } = useNaiveForm();
const { label, isCounting, loading, getEmailCaptcha } = useCaptcha();

interface FormModel {
  mailAccount: string;
  verifyCode: string;
}

const model: FormModel = reactive({
  mailAccount: '1980184135@qq.com',
  verifyCode: ''
});

const rules = computed<Record<keyof FormModel, App.Global.FormRule[]>>(() => {
  const { formRules } = useFormRules();

  return {
    mailAccount: formRules.email,
    verifyCode: formRules.emailCaptcha
  };
});

async function handleSubmit() {
  await validate();
  // request
  await authStore.loginWithEmail(model.mailAccount, model.verifyCode);

  // window.$message?.success($t('page.login.common.validateSuccess'));
}
</script>

<template>
  <NForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false">
    <NFormItem path="mailAccount">
      <NInput v-model:value="model.mailAccount" :placeholder="$t('page.login.common.emailPlaceholder')">
        <template #prefix>
          <icon-local-email-icon class="text-24px text-primary" />
        </template>
      </NInput>
    </NFormItem>
    <NFormItem path="verifyCode">
      <div class="w-full flex-y-center gap-16px">
        <NInput
          v-model:value="model.verifyCode"
          :placeholder="$t('page.login.common.codePlaceholder')"
          @keyup.enter="handleSubmit"
        >
          <template #prefix>
            <icon-local-shield-icon class="text-24px text-primary" />
          </template>
        </NInput>
        <NButton size="large" :disabled="isCounting" :loading="loading" @click="getEmailCaptcha(model.mailAccount)">
          {{ label }}
        </NButton>
      </div>
    </NFormItem>
    <NSpace vertical :size="18" class="w-full">
      <NButton type="primary" size="large" round block @click="handleSubmit">
        {{ $t('common.confirm') }}
      </NButton>
      <NButton size="large" round block @click="toggleLoginModule('pwd-login')">
        {{ $t('page.login.common.back') }}
      </NButton>
    </NSpace>
  </NForm>
</template>

<style scoped></style>
